import VueRouter from "vue-router"
import Vue from "vue"
import {getToken,deleteToken} from "@/utils/auth"
// import store from "@/store"
Vue.use(VueRouter)

// 增强路由push方法
// const enhance = VueRouter.prototype.push

// VueRouter.prototype.push = function(local,okCallback,errorCallback){
//     if(okCallback || errorCallback){
//          enhance.call(this,local,okCallback,errorCallback)
//     }else{
//         enhance.call(this,local).catch(()=>{})
//     }
// }

// 封装路由方法增强
function enhance(source,type){
    const origin = source.prototype[type]
    source.prototype[type] = function(local,okCallback,errorCallback){
    if(okCallback || errorCallback){
        origin.call(this,local,okCallback,errorCallback)
    }else{
        origin.call(this,local).catch(()=>{})
    }
}
}

enhance(VueRouter,"push")
enhance(VueRouter,"replace")

import routes from "./routes"
import store from "@/store"


let route = new VueRouter({
    mode:"history",
    routes,
    scrollBehavior(a,b,c){
        if(c){
            return c
        }else{
            return {x:0,y:0}
        }
    }
})

let newRoute = ["/trade","/pay"]
// 全局前置路由守卫
route.beforeEach(async (to,from,next)=>{
    let token = getToken()
    if(token){
        // 获取vuex中的数据
        let userInfo = store.state.user.userInfo
        // console.log(userInfo);
        // 判断userInfo
        if(userInfo.id){
            next()
        }else{
            try {
                await store.dispatch("user/getUserInfo")
                next()
            } catch (error) {
                // 删除本地token
                deleteToken()
                // 跳转登录页
                next("/login")
            }   
        }
    }else{
        // token不存在  不允许访问敏感路由  其他路由正常放行
        if(newRoute.includes(to.path)){
            next("/login")
        }
        next()
    }
    next()
})
export default route